package StudyCode.summary.BufferAndChannel;

import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.Pipe;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class TestPipeObjectsUsingWorkerThread {
	public static void main(String[] argv) throws Exception {
		WritableByteChannel out = Channels.newChannel(System.out);
		ReadableByteChannel workerChannel = startWorker(10);
		ByteBuffer buffer = ByteBuffer.allocate(100);

		while (workerChannel.read(buffer) >= 0) {
			buffer.flip();
			out.write(buffer);
			buffer.clear();
		}
	}

	private static ReadableByteChannel startWorker(int reps) throws Exception {
		Pipe pipe = Pipe.open();
		Worker worker = new Worker(pipe.sink(), reps);
		worker.start();
		return (pipe.source());
	}

	private static class Worker extends Thread {
		WritableByteChannel channel;
		private int reps;

		Worker(WritableByteChannel channel, int reps) {
			this.channel = channel;
			this.reps = reps;
		}

		public void run() {
			ByteBuffer buffer = ByteBuffer.allocate(100);

			try {
				for (int i = 0; i < this.reps; i++) {
					doSomeWork(buffer);
					while (channel.write(buffer) > 0) {
					}
				}

				this.channel.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		private void doSomeWork(ByteBuffer buffer) {
			buffer.clear();
			buffer.put("www.tah1986.com".getBytes());
			buffer.put("\r\n".getBytes());
			buffer.flip();
		}
	}
}
